<?php
/**
 * Created by PhpStorm.
 * User: 93933
 * Date: 2021/11/2
 * Time: 19:10
 */
namespace catchAdmin\api\controller;

use catchAdmin\api\request\TokenRequest;
use catchAdmin\api\service\IndexService;
use catchAdmin\customs\model\CnOrder;
use catchAdmin\api\model\Order as customsOrder;
use catchAdmin\api\model\OrderSon as customsOrderSon;
use catchAdmin\customs\model\XsOrder;
use catchAdmin\externalGoods\model\GoodsRule;
use catchAdmin\externalGoods\service\TenantGoodsService;
use \think\Request;
use catcher\base\CatchController;
use catcher\CatchResponse;
use think\facade\Db;
use catcher\Code;
use thans\jwt\facade\JWTAuth;
use xinsheng\api\v1\Pay;
use catchAdmin\externalGoods\model\Goods as externalGoodsModel;


class Index extends CatchController
{
    protected $merchantInfo;
    protected $_par = ['_merCode'=>'10000000863',
        '_public_key'=>'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJFkdpM39EbL36SwGUi6LBpXE9kVfX1z4r7NZkJUArJPGkblCs1gW919eAchOZhKOP9eBGAc6KTK0qArujjb+bg69Xl3sqJq0xZJBR1SJbLFI/rV7p0J92crC9ymiGsECM+7DkZS8UXLZeO1aSt59KTgnpfyOX7s4XjMnOS6MbPQIDAQAB'];

    /**
     * 获取token
     * @param TokenRequest $request
     * @return string
     */
    public function getToken(TokenRequest $request)
    {

        try {
              $params = $request->param();
              //写入日志处理
              $this->writeLog('login',json_encode($params,JSON_UNESCAPED_UNICODE));

              $beginToday = mktime(0,0,0,date('m'),date('d'),date('Y'));
              $endToday = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
              if($params['timeStamp'] > $endToday||$params['timeStamp'] < $beginToday){
                  return $this->commonReturn('login', ['code'=> Code::LOGIN_FAILED, 'msg'=> '过期的时间戳']);

              }
              $info = Db::table('users')
                  ->field('id as customs_id,tenant_id,merchant_id,merchant_name,merchant_secret')
                  ->where(['merchant_id' => $params['merchantId'],'type'=>2])
                  ->find();

              if(!$info) {
                  return $this->commonReturn('login', ['code'=> Code::LOGIN_FAILED, 'msg'=> '商户号不存在']);
              }

              $signList = $this->get_sign($params, $info['merchant_secret']);
              if($signList['sign'] !== $params['sign']){

                  return $this->commonReturn('login', ['code'=> Code::SIGN_ERROR, 'msg'=> '签名错误，请检查参数、密钥及签名方式']);

              }
              unset($info['merchant_secret']);
              $token = $this->jwt($info);
              return $this->commonReturn('login', ['code'=> Code::SUCCESS, 'msg'=> '获取token成功', 'data' => [ 'token' => $token]]);

        } catch (\Exception $exception) {

            return $this->commonReturn('login', ['code'=> Code::LOGIN_FAILED, 'msg'=> $exception->getMessage()]);

        }
    }

    /**
     * 获取token
     * @param Request $request
     * @return string
     */
    public function orderService(Request $request)
    {

        try {
            //获取参数
            $serviceType = $request->param('serviceType');
            $data = $request->post('data');
            //var_dump(file_get_contents('php://input')); //接受row数据
            //写入日志处理
            $this->writeLog('order',$data);

            //验证token
            $auth = JWTAuth::auth();
            $this->merchantInfo = json_decode(json_encode($auth['merchantInfo']),true);//验证token

            if(!$request->has('data','post')){
                return $this->commonReturn('order',['code'=>Code::FAILED, 'msg'=>'缺少data']);

            }

            //处理data
            $data = json_decode($data,true);
            if(!$data||!is_array($data)){
                return $this->commonReturn('order',['code'=>Code::FAILED, 'msg'=>'data格式错误']);
            }

            //方法分发
            switch ($serviceType)
            {
                //订单推送
                case 'pushOrder':
                    $result = $this->pushOrder($data);
                break;
                //订单查询
                case 'queryOrder':
                    $result = $this->queryOrder($data);
                    break;
                //订单取消
                case 'cancelOrder':
                    $result = $this->cancelOrder($data);
                    break;
                case 'pushOrder2'://候鸟推送
                    $result = $this->pushOrder2($data);
                    break;
//                case 'pushOrder3'://新生支付
//                    $result = $this->pushOrder3($data);
//                    break;
                case 'pushOrder4'://菜鸟推送
                    $result = $this->pushOrder4($data);
                    break;
                case 'pushJKOrder'://吉客运
                    $result = $this->pushJKOrder($data);
                    break;
                default:
                    $result = ['code'=>Code::FAILED, 'msg'=>'未定义的服务'];
            }

            return $this->commonReturn('order',$result);

        } catch (\Exception $exception) {
            return $this->commonReturn('order',['code'=>Code::FAILED, 'msg'=> $exception->getMessage()]);

        }

    }
    /**
     * 统一返回
     * @param $result
     * @param $type
     * @return string
     */
    protected function commonReturn($type,$result)
    {
        //写入日志处理
        $this->writeLog($type, json_encode($result,JSON_UNESCAPED_UNICODE));

        if($result['code'] === 10000){
            return CatchResponse::success($result['data'], $result['msg'], $result['code']);

        }else{
            return CatchResponse::fail($result['msg'],$result['code']);

        }

    }

    //菜鸟订单
    protected function pushOrder4($data)
    {
        $keys = [
            'ownerUserId',
            'businessUnitId',
            'orderType',
            'storeCode',
            'externalShopName',
            'orderSource',
            'orderCreateTime',
            'orderPayTime',
            'saleMode',
            'receiverInfo',
            'senderInfo',
            'refunderInfo',
            'goodsTotalPrice',
            'coupon',
            'insurance',
            'postFee',
            'orderAmountInfo',
            'customsDeclareInfo',
            'businessUnitId',
            'externalOrderCode'
        ];
        $value = $this->check_fields($data, $keys, true);//验证字段
        //判断参数

        if(!is_array($value)){
            return [ 'code'=>Code::FAILED , 'msg'=> $value];
        }

        $order  = (new customsOrder)
            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
            ->where([
//                'tenant_id' =>$this->merchantInfo['tenant_id'],
                'externalOrderCode' =>$data['externalOrderCode']
            ])
            ->find();

        if($order){
            return [ 'code'=>Code::FAILED , 'msg'=> "订单编号{$data['externalOrderCode']}已存在"];
        }

        ///计算参数
        $goodsTotalPrice = $data['goodsTotalPrice'];//商品总价，申报金额
        $coupon = $data['coupon'];//优惠金额
        $insurance = $data['insurance'];//保险费
        $postFee = $data['postFee'];//运费

        $dutiablePrice = dutiablePrice($insurance,$postFee,$goodsTotalPrice) ;//订单完税总价
        $customsTax = customsTax($dutiablePrice ,0,1);//关税
        $consumptionTax = consumptionTax($dutiablePrice,$customsTax,0.091,1);//消费税金额
        $vat = vat($dutiablePrice,$customsTax,$consumptionTax,0,1);//增值税
        $totalTax = totalTax($customsTax,$consumptionTax,$vat);//综合税
        $actualPayment = actualPayment($dutiablePrice,$totalTax,$coupon);//消费者实付金额

        $data['orderAmountInfo'] = [
            'dutiablePrice'=>priceFormat($dutiablePrice),//订单完税总价
            'coupon'=>priceFormat($coupon),//优惠金额
            'consumptionTax'=>priceFormat($consumptionTax),//消费税金额
            'postFee'=>priceFormat($postFee),//运费
            'vat'=>priceFormat($vat),//增值税
            'customsTax'=>priceFormat($customsTax),//关税
            'actualPayment'=> priceFormat($actualPayment),
            'totalTax'=>priceFormat($totalTax),
            'insurance'=>priceFormat($insurance),
            'currency'=>'CNY'
        ];//订单金额信息

        //$this->content['externalOrderCode'] = Str::random(20,1);

        foreach ($data['orderItemList'] as $key => &$value){
            $temp = [];
            $temp['itemId'] = $value['itemId'];
            $temp['itemQuantity'] = $value['itemQuantity'];
            $temp['totalPrice'] = $value['totalPrice'];//商品申报货值
            $temp['itemTotalActualPrice'] = $value['itemTotalActualPrice'];//商品总价 优惠后
            $temp['itemTotalPrice'] = $value['itemTotalPrice'];//商品总价 优惠前

            $dutiablePrice = dutiablePrice(0,0,$temp['totalPrice']) ;//订单完税总价
            $customsTax = customsTax($dutiablePrice ,0,1);//关税
            $consumptionTax = consumptionTax($dutiablePrice,$customsTax,0.091,1);//消费税金额
            $vat = vat($dutiablePrice,$customsTax,$consumptionTax,0,1);//增值税
            $totalTax = totalTax($customsTax,$consumptionTax,$vat);//综合税

            $value['declareInfo']= [
                'customsTax'=>priceFormat($customsTax),//商品关税
                'consumptionTax'=>priceFormat($consumptionTax),//商品消费税
                'totalTax'=>priceFormat($totalTax),//商品综合税
                'itemTotalActualPrice'=>priceFormat($temp['itemTotalActualPrice']),//商品总价优惠后
                'itemTotalPrice'=>priceFormat($temp['itemTotalPrice']),//商品总价优惠前
                'vat'=>$vat
            ];
            unset($data['orderItemList'][$key]['totalPrice'],$data['orderItemList'][$key]['itemTotalActualPrice'],$data['orderItemList'][$key]['itemTotalPrice']);
            //$value = $temp;
        }
//        $data['externalOrderCode'] = Str::random(20,1);

        unset($data['goodsTotalPrice']);
        unset($data['coupon']);
        unset($data['insurance']);
        unset($data['postFee']);


        $data['receiverInfo'] =   array_key_exists('receiverInfo',$data) ? json_encode($data['receiverInfo'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        $data['senderInfo'] =  array_key_exists('senderInfo',$data) ? json_encode($data['senderInfo'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        $data['refunderInfo'] =  array_key_exists('refunderInfo',$data) ? json_encode($data['refunderInfo'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        $data['orderAmountInfo'] =  array_key_exists('orderAmountInfo',$data) ? json_encode($data['orderAmountInfo'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        $data['customsDeclareInfo'] =  array_key_exists('customsDeclareInfo',$data) ? json_encode($data['customsDeclareInfo'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        //$data['orderItemList'] =  array_key_exists('orderItemList',$data) ? json_encode($data['orderItemList'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        //
        $data['extendFields'] =   array_key_exists('extendFields',$data)   ? json_encode($data['extendFields'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        $data['departureInfo'] =   array_key_exists('departureInfo',$data)  ? json_encode($data['departureInfo'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        $data['logisticsServices'] =   array_key_exists('logisticsServices',$data)  ? json_encode($data['logisticsServices'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        $data['packageInfo'] =   array_key_exists('packageInfo',$data)  ? json_encode($data['packageInfo'],JSON_UNESCAPED_UNICODE) : json_encode([]);
        //
        $data['_ext_data'] = json_encode($data);
        $data['tenant_id'] =  $this->merchantInfo['tenant_id'];



        $ext_field_receiverInfo = json_decode($data['receiverInfo'],true);
        //$ext_field_orderItemList = json_decode($data['orderItemList'],true);
        $ext_field_orderItemList = $data['orderItemList'];
        $ext_field_orderAmountInfo = json_decode($data['orderAmountInfo'],true);
        $ext_field_customsDeclareInfo = json_decode($data['customsDeclareInfo'],true);//通关申报信息

        //补充字段
        $data['orderId'] = $data['externalOrderCode'];//订单号
        $data['orderDate'] = $data['orderCreateTime'];//订单日期
        $data['contactName'] = $ext_field_receiverInfo['name'];//收货人昵称
        $data['contactMobile'] = $ext_field_receiverInfo['contactNo'];//收货人手机号码
        $data['contactAddr'] = implode('-',[ $ext_field_receiverInfo['province'],$ext_field_receiverInfo['city'],$ext_field_receiverInfo['district'] ]) ;//收货人省市区
        $data['detailAddr'] =   $ext_field_receiverInfo['address'];//详细地址

        //$snum = 0;//商品总数量
        $orderList = [];
        foreach ($ext_field_orderItemList as $key => $value){
          //  $snum += $value['itemQuantity'];
            $orderList[$key]['orderId'] = $data['orderId'];
            $orderList[$key]['productId'] = $value['itemId'];
            $orderList[$key]['price'] = number_format(($value['declareInfo']['itemTotalActualPrice'] / $value['itemQuantity'] ) /100 ,2);
            $orderList[$key]['amount'] = $value['declareInfo']['itemTotalActualPrice'];
            $orderList[$key]['num'] = $value['itemQuantity'];
        }


        //$data['snum'] = $snum;//商品总数量
        //$data['realPayment'] =  number_format( $ext_field_orderAmountInfo['actualPayment'] / 100 ,2);//实际付款金额
        $data['amount'] =   number_format($ext_field_orderAmountInfo['dutiablePrice'] / 100 , 2);//商品金额
        $data['distributionfee'] =   number_format($ext_field_orderAmountInfo['postFee'] / 100 ,2 );//运费
        $data['discount'] =   number_format($ext_field_orderAmountInfo['coupon'] / 100 ,2);//非现金抵扣金额

        $data['buyerName'] =   $ext_field_customsDeclareInfo['buyerName'];//订购人姓名
        $data['ConsigneeCode'] =   $ext_field_customsDeclareInfo['buyerIDNo'];//订购人证件号

        $data['_order_type'] = 3;

        //dd($data);

        Db::startTrans();
        try {


            $apiPayData = [];

            $apiPayData['merOrderId'] = $data['orderId'];
            $apiPayData['displayName'] = '跨进电商商品前台展示名称';
            $apiPayData['goodsName'] = '跨进电商商品名称';
            $apiPayData['goodsCount'] = array_sum(array_column($data['orderItemList'],'itemQuantity')) ;
            $apiPayData['goodsType'] = '06';
            $apiPayData['orderAmount'] =  (int) ($goodsTotalPrice * 100);
            $apiPayData['orderCurrencyCode'] = 'CNY';
            $apiPayData['tradeType'] = $data['tradeType'];
            $apiPayData['payType'] = '4';
            $apiPayData['orgCode'] = 'WECHATPAY';
            $apiPayData['payCurrencyCode'] = 'CNY';
            $apiPayData['settleCurrencyCode'] = 'CNY';
            $apiPayData['shareFlag'] = '0';
            $apiPayData['returnUrl'] = 'http://cross.qekj.net/callback/xinsheng';
            $apiPayData['noticeUrl'] = 'http://cross.qekj.net/callback/xinsheng';
            $apiPayData['customerType'] = '1';
            $apiPayData['customerName'] = $data['buyerName'];
            $apiPayData['customerIdNo'] = $data['ConsigneeCode'];
            $apiPayData['customerTel'] = $data['contactMobile'];

            $xinshengApi = (new Pay);
            $result = $xinshengApi->apiPay($apiPayData);

            //dd($result);

            $data = array_merge($data,$apiPayData, [
                '_xs_apipay_return_data'=>$result['content'],
                'xs_status'=>$result['content']['status'],
                'dealId'=>$result['content']['dealId'],
                '_random_orderId'=>$result['head']['orderId'],
                'tenant_id'=>$this->merchantInfo['tenant_id'],
            ]);

            //扩展字段
            //补充字段
            //$insert['orderId'] = $data['merOrderId'];

            $data['orderDate'] = date('Y-m-d H:i:s') ;//订单日期
            $data['contactAddr'] = '';//省市区
            $data['detailAddr'] =  '';//详细地址

            //$value['realPayment'] =  number_format($result['content']['payAmount']  / 100 ,2);;//实际付款金额


            $data['_ext_data'] = $data;


            $model = new customsOrder();
            $model->save($data);

            $customsOrderSonModle = new customsOrderSon;
            $customsOrderSonModle->saveAll($orderList);

            // 提交事务
            Db::commit();
            return [ 'code'=>Code::SUCCESS , 'msg'=> '新增成功' , 'data'=>[]];
        } catch (\Exception $e) {
            Db::rollback();
            return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
        }
    }

    //新生支付推送
    protected function pushOrder3($data){
        $keys = ['merOrderId','displayName','goodsName','goodsCount','goodsType','orderAmount','orderCurrencyCode','tradeType',
            'payType','orgCode','payCurrencyCode','settleCurrencyCode','shareFlag','returnUrl','noticeUrl','customerType','customerName','customerIdNo','customerTel'];
        $value = $this->check_fields($data, $keys, true);//验证字段
        //判断参数

        if(!is_array($value)){
            return [ 'code'=>Code::FAILED , 'msg'=> $value];
        }

        $xinshengApi = new Pay();

        $data['returnUrl'] = "http://cross.qekj.net/callback/xinsheng";
        $data['noticeUrl'] = "http://cross.qekj.net/callback/xinsheng";


        $order  = (new customsOrder)
            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
            ->where([
//                'tenant_id' =>$this->merchantInfo['tenant_id'],
                'orderId' =>$data['merOrderId']
            ])
            ->find();

        if($order){
            return [ 'code'=>Code::FAILED , 'msg'=> "订单编号{$data['merOrderId']}已存在"];
        }

        $ebpCode = array_key_exists('ebpCode',$data) ? $data['ebpCode'] : '';
        $ebpName = array_key_exists('ebpName',$data) ? $data['ebpName'] : '';
        $paycomCode = array_key_exists('paycomCode',$data) ? $data['paycomCode'] : '';
        $paycomName = array_key_exists('paycomName',$data) ? $data['paycomName'] : '';

        unset($data['ebpCode']);
        unset($data['ebpName']);
        unset($data['paycomCode']);
        unset($data['paycomName']);

        Db::startTrans();
        try {
            $result = $xinshengApi->apiPay($data);

            $insert = array_merge($data,[
                '_ext_data'=>$data,
                '_return_data'=>$result['content'],
                'xs_status'=>$result['content']['status'],
                'dealId'=>$result['content']['dealId'],
                '_random_orderId'=>$result['head']['orderId'],
                'tenant_id'=>$this->merchantInfo['tenant_id'],
            ]);

            //扩展字段
            //补充字段
            $insert['orderId'] = $data['merOrderId'];

            $insert['orderDate'] = date('Y-m-d H:i:s') ;//订单日期
            $insert['contactName'] = $data['customerName'];//收货人昵称
            $insert['contactMobile'] = $data['customerTel'];//收货人手机号码
            $insert['contactAddr'] = '';//省市区
            $insert['detailAddr'] =  '';//详细地址

            $insert['realPayment'] =  number_format($data['orderAmount']  / 100 ,2);;//实际付款金额
            $insert['amount'] =  number_format($data['orderAmount']  / 100 ,2);//商品金额
//            $insert['distributionfee'] =   ;//运费
//            $insert['discount'] =   $data['discount'];//非现金抵扣金额

            $insert['buyerName'] =   $data['customerName'];//订购人姓名
            $insert['ConsigneeCode'] =   $data['customerIdNo'];//订购人证件号

            $insert['_order_type'] = 2;

            $insert['ebpCode'] = $ebpCode;
            $insert['ebpName'] = $ebpName;
            $insert['paycomCode'] = $paycomCode;
            $insert['paycomName'] = $paycomName;

            (new customsOrder)->save($insert);


            $orderSonInsert = [];
            $orderSonInsert['orderId'] = $insert['orderId'];
            $orderSonInsert['price'] = number_format(($insert['orderAmount'] / $insert['goodsCount']) / 100 ,2);
            $orderSonInsert['amount'] = $insert['orderAmount'];
            $orderSonInsert['num'] = $insert['goodsCount'];
            $orderSonInsert['goods_name'] = $insert['goodsName'];


            (new customsOrderSon)->save($orderSonInsert);

            // 提交事务
            Db::commit();
            return [ 'code'=>Code::SUCCESS , 'msg'=> '新增成功' , 'data'=>[]];
        } catch (\Exception $e) {
            Db::rollback();
            dd($e->getMessage());
            return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
        }

    }



//    //新生支付推送
//    protected function pushOrder3($data){
//        $orderData = [];//主订单信息
//        $orderSonData = [];//子订单信息
//
//        //订单字段
//        $orderKeys = ['orderId','erportCode','eCompanyCode','eCompanyName','payTransactionNo','actionType','payerName','payerId'];
//
//        //订单商品字段
//        $goodsKeys = ['subOrderNo','realPayment'];
//
//        $msg = "";
//        foreach ($data as $key => $value){
//            $checkValueResult = $this->check_fields($value, $orderKeys,true);//验证字段
//            //判断参数
//            if(!is_array($checkValueResult)){
//                $msg = 'data['.$key .']'.$checkValueResult;
//                break;
//            }
//            $flag = Db::table('db_customs_order')
//                ->field('id')
//                ->where(['orderId' => $value['orderId'], 'deleteStatus' => 0, 'status' => 0, 'tenant_id' => $this->merchantInfo['tenant_id']])
//                ->find();
//            if($flag){
//                $msg = '订单号'.$value['orderId'].'已存在';
//                break;
//            }
//
//            if(!empty($value['orderDetails'])){
//                foreach ($value['orderDetails'] as $k => &$v){
//                    $checkVResult = $this->check_fields($v, $goodsKeys,true);//验证字段
//                    //判断参数
//                    if(!is_array($checkVResult)){
//                        $msg = 'data['.$key .'],'.'orderDetails['.$k .'],'.$checkVResult;
//                        break 2;
//                    }
//
//                    $v['orderId'] = $value['orderId'];
//                    $v['amout'] = $value['realPayment'];
//                    $v['subOrderNo'] = $value['subOrderNo'];
//                    $v['goods_name'] = $value['goodsName'] ?? '';
//                    $v['num'] = $value['goodsCount'] ?? '';
//                    $v['_logisticsCompany'] = $value['logisticsCompany'] ?? '';
//                    $v['_logisticsNo'] = $value['logisticsNo'] ?? '';
//                    $orderSonData[] = $v;
//                }
//            }else{
//                $orderSonData[] = [
//                    'orderId'=>$value['orderId'],
//                    'amout'=>$value['realPayment'],
//                    'num'=>1
//                ];
//            }
//
//            $value['tenant_id'] = $this->merchantInfo['tenant_id'];//电商商户
//            unset($value['goodsInfo']);
//            $orderData[] = $value;
//            unset($value);
//        }
//
//        //dd($orderData);
//
//        if($msg !== ""){
//            return [ 'code'=>Code::FAILED , 'msg'=> $msg ];
//        }
//
//        if(count($orderData)>0){
//            foreach ($orderData as &$value){
//                //dd($value);
//                $temp = [];
//                $temp['_order_type'] = 2;//订单类型 2新生支付订单
//                $temp['tenant_id'] = $value['tenant_id'];
//                $temp['orderId'] = $value['orderId'];
//
//                $temp['_erportCode'] = $value['erportCode'];//港口代码
//                $temp['ebpCode'] = $value['eCompanyCode'];//电商平台备案号
//                $temp['ebpName'] = $value['eCompanyName'];//电商平台备案名称
//
//                $temp['_customsCode'] = $value['customsCode'] ?? '';//广州口岸代码
//                $temp['_intype'] = $value['intype'] ?? '';//1：保税进口
//                $temp['payOrderNo'] = $value['payTransactionNo'];//支付交易号
//                $temp['_actionType'] = $value['actionType'];//操作类型
//                //报关业务
//                $temp['buyerName'] = $value['payerName'] ?? '';//订购人
//                $temp['ConsigneeCode'] = $value['payerId'] ?? '';//订购人身份证
//                $temp['contactMobile'] = $value['payerPhoneNumber'] ?? '';//订购人手机号码
//
//                $temp['contactName'] = $value['payerName'];
//                $temp['contactCode'] = $value['payerId'] ?? '';
//
//                $temp['area_id'] = $value['area_id'] ?? '';
//                $temp['detailAddr'] = $value['user_address'] ?? '';
//                $temp['note'] = $value['remark'] ?? '';
//                $temp['orderDate'] = date("Y-m-d H:i:s");
//                $temp['realPayment'] = $value['realPayment'] ?? '';
//
//                $temp['_ext_data'] = json_encode(array_merge($temp,$value));
//                $value = $temp;
//            }
//
////            if(count($orderSonData) > 0) {
////                foreach ($orderSonData as &$value) {
////                    $temp = [];
//////                $temp['tenant_id'] = $value['tenant_id'];
////                    $temp['orderId'] = $value['orderId'];
////
////                    $temp['subOrderNo'] = $value['subOrderNo'];
////                    $temp['payAmount'] = $value['payAmount'];
////                    $temp['goodsName'] = $value['goodsName'];
////                    $temp['goodsCount'] = $value['goodsCount'];
////                    $temp['logisticsCompany'] = $value['logisticsCompany'];
////                    $temp['logisticsNo'] = $value['logisticsNo'];
////                    $value = $temp;
////                }
////            }
//            // dd($orderData,$orderSonData);
//
//            // 启动事务
//            Db::startTrans();
//            try {
//                $res1 = Db::table('db_customs_order')->limit(200)->insertAll($orderData);
//                $res2 = Db::table('db_customs_orderlist')->limit(200)->insertAll($orderSonData);
//
//                if($res1&&$res2){
//                    // 提交事务
//                    Db::commit();
//                    return [ 'code'=>Code::SUCCESS , 'msg'=> '新增成功' , 'data'=>[]];
//                }else{
//                    Db::rollback();
//                    return [ 'code'=>Code::FAILED , 'msg'=> '新增失败'];
//                }
//
//            } catch (\Exception $e) {
//
//                return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
//                // 回滚事务
//                Db::rollback();
//            }
//        }else{
//            return [ 'code'=>Code::FAILED , 'msg'=> '没有订单或商品数据'];
//
//        }
//    }

    //候鸟推送
    protected function pushOrder2($data)
    {
        $orderData = [];//主订单信息
        $orderSonData = [];//子订单信息
        $needUpdateOrder = [];

        //订单字段 订单号、、、
        //contactName = username 收件人姓名
        //contactMobile = user_phone 收件人手机号
        //detailAddr = user_address 收件人手机号
        //amount =  商品总价额
        //distributionfee = amount_freight 运费
        //discount =  amount_discount 非现金抵扣金额 优惠
        //realPayment =  amount_paid_in 实际支付金额
        //contactCode =  id_card 收件人身份证号码
        //buyerName =  declarer 订购人姓名
        //ConsigneeCode =  declarer_id_card 订购人证件号
        //payOrderNo =  pay_no 支付交易号
        $orderKeys = ['orderId','contactName','contactMobile','area_id','detailAddr','order_goods', 'amount', 'distributionfee', 'discount', 'realPayment','ebpCode','ebpName','paycomCode','paycomName','payOrderNo','contactAddr'];
        //保税
        $orderKeys_1 = ['contactCode','buyerName','ConsigneeCode','source_platform_no','pay_type','pay_time'];
        //香港直邮
        $orderKeys_4 = ['contactCode'];
        //海外直邮
        $orderKeys_5 = ['contactCode','id_card_front_img','id_card_back_img'];

        //$orderKeys = ['payerAccount','username','user_phone','area_id','user_address','orderId','order_goods', 'amount', 'distributionfee', 'discount', 'realPayment'];

        //订单商品字段
        $goodsKeys = ['goods_spu','sku_id','goods_num','goods_price'];
//        $goodsKeys_1 = ['goods_spu','sku_id','goods_num','goods_price'];

        $systGoodsModel = new externalGoodsModel;

        $msg = "";
        foreach ($data as $key => $value){
            $checkValueResult = $this->check_fields($value, $orderKeys,true);//验证字段
            //判断参数
            if(!is_array($checkValueResult)){
                $msg = 'data['.$key .']'.$checkValueResult;
                break;
            }

            //2.判断订单号是否已经存在
            $flag = Db::table('db_customs_order')
                ->field('id')
                ->where(['orderId' => $value['orderId'], 'deleteStatus' => 0, 'status' => 0, 'tenant_id' => $this->merchantInfo['tenant_id']])
                ->find();
            if($flag){
                $msg = '订单号'.$value['orderId'].'已存在';
                break;
            }

            $all_goods_spu_arr = array_column($value['order_goods'],'goods_spu');
            $goods_spu_trade_type_arr = $systGoodsModel->where('goods_spu','in',$all_goods_spu_arr)->column('trade_type_id');
            //3.订单商品，多个商品，判断都是同一类型
            if(1 < count($value['order_goods'])){
                $IndexService = new IndexService;
                if($IndexService->checkTwoTradeType($goods_spu_trade_type_arr)){
                    $msg = '贸易类型错误、存在多种贸易类型（跨境+非跨境）';
                    break;
                }
                //判断跨境商品是否只能单个提交
                if(!empty(array_intersect([1, 4, 5], $goods_spu_trade_type_arr))){
                    $msg = '跨境商品，只支持一单一品';
                    break;
                }
            }

            //if(!empty(array_intersect($goods_spu_trade_type_arr,[1]))){ //只有保税直供。 跨境商品，需要推送支付单
            if(!empty(array_intersect($goods_spu_trade_type_arr,[1,4,5]))){
                //只有保税直供。 跨境商品，需要推送支付单
                //2024 0518修改为 这三种贸易类型都需要推送支付单（候鸟仅保税需要，其他可以无视）
                $value['is_need_push_payment_order'] = 1;
                $value['tradeType'] = '0004';
            }else{
                $value['tradeType'] = '0002';
            }

            foreach ($value['order_goods'] as $k => &$v){
                $trade_type_id = $systGoodsModel->where('goods_spu',$v['goods_spu'])->value('trade_type_id');
                if(1 == $trade_type_id){
                    $checkVResult1 = $this->check_fields($value, $orderKeys_1,true);//验证字段
                }elseif (4 == $trade_type_id){
                    $checkVResult1 = $this->check_fields($value, $orderKeys_4,true);//验证字段
                }elseif (5 == $trade_type_id){
                    $checkVResult1 = $this->check_fields($value, $orderKeys_5,true);//验证字段
                }elseif(null == $trade_type_id){
                    $msg = '商品spu错误、或者商品贸易类型错误';
                    break;
                }else{
                    $checkVResult1 = [];
                }

                if(!is_array($checkVResult1)){
                    $msg = 'data['.$key .']'.$checkVResult1;
                    break 2;
                }

                $checkVResult = $this->check_fields($v, $goodsKeys,true);//验证字段
                if(!is_array($checkVResult)){
                    $msg = 'data['.$key .'],'.'order_goods['.$k .'],'.$checkVResult;
                    break 2;
                }

                $v['orderId'] = $value['orderId'];
                $orderSonData[] = $v;
            }
            $value['tenant_id'] = $this->merchantInfo['tenant_id'];//电商商户
            unset($value['goodsInfo']);
            $orderData[] = $value;
            unset($value);
        }

        //dd($orderData);

        if($msg !== ""){
            return [ 'code'=>Code::FAILED , 'msg'=> $msg ];
        }

        if(count($orderData)>0 && count($orderSonData)>0){
            foreach ($orderData as &$value){
                //dd($value);
                $temp = [];
                $temp['_order_type'] = 1;//订单类型 1候鸟订单
                $temp['tenant_id'] = $value['tenant_id'];
                $temp['orderId'] = $value['orderId'];//订单iD
//                $temp['source_platform_no'] = $value['source_platform_no'] ?? '';//申报订单编号

                //订单默认日期
                if(array_key_exists('orderDate',$value)){
                    $temp['orderDate'] =   date("Y-m-d H:i:s",strtotime($value['orderDate'])  ?? time());
                }else{
                    $temp['orderDate'] = date("Y-m-d H:i:s");
                }

                $temp['create_time'] = strtotime($temp['orderDate']);

                if('000000' != $value['area_id']){
                    $isActiveAreaId = Db::table('db_syst_sync_areas')->where('pid',$value['area_id'])->count();
                    $isActiveAreaId2 = Db::table('db_syst_sync_areas')->where('area_id',$value['area_id'])->find();

                    if($isActiveAreaId > 0 || empty($isActiveAreaId2)){
                        return [ 'code'=>Code::FAILED , 'msg'=> '区域ID不存在，或者区域ID不是最下级'];
                    }
                }else{
                    //收货地址
                    $area_id = Db::table('db_syst_sync_areas')->where('full_area_name',$value['full_area_name'])->value('area_id');
                    if(empty($area_id))   return [ 'code'=>Code::FAILED , 'msg'=> '收货地址区划错误，直辖市精确到街道，其他精确到区/县'];

                    //如果是直辖市，直接取街道的地址
                    $area_son_id =  Db::table('db_syst_sync_areas')->where('pid',$area_id)->value('area_id');
                    if($area_son_id) $area_id = $area_son_id;
                    $value['area_id'] = $area_id;
                    unset($value['full_area_name']);
                }


                $temp['HNACARD'] = array_key_exists('HNACARD',$value) ? $value['HNACARD'] : '0';

                //扩展数据
                $temp['_ext_data'] = json_encode(array_merge($temp,$value));
                $value = array_merge($value,$temp);

//                $value = $temp;
            }

            foreach ($orderSonData as $key => &$value){
                $temp = [];
                $no = $key + 1;
//                $temp['tenant_id'] = $value['tenant_id'];
                $temp['orderId'] = $value['orderId'];
                $temp['orderlistId'] = $value['orderId'] . "_" . $no;
//                $temp['productId'] = $value['goods_spu'] . ',' . $value['sku_id'];
                $temp['productId'] = $value['goods_spu'];
                $temp['num'] = $value['goods_num'];

//                $goods_info = Db::table('db_syst_sync_goods_rule sr')
                $goods_info = Db::table('db_tenant_goods_rule sr')
                    ->field('sr.sku_name,sg.goods_name,sg.is_sale,sg.stock,sr.sku_stock,sr.sku_price,sg.trade_type_name,sg.goods_img,sg.supplier_id')
                    ->leftJoin('db_tenant_goods sg','sr.goods_id = sg.id')
                    ->where('sr.goods_spu',$value['goods_spu'])
                    ->where('sr.goods_sku',$value['sku_id'])
                    ->where('sr.tenant_id',$this->merchantInfo['tenant_id'])
                    ->where('sg.deleted_at',0)
                    ->order('sr.id','desc')
                    ->find();
                if(!$goods_info){
                    return [ 'code'=>Code::FAILED , 'msg'=> '商品未添加、或商品不存在该spu或sku' ];
                }
                if($goods_info['is_sale'] != 1){
                    return [ 'code'=>Code::FAILED , 'msg'=> '商品已下架' ];
                }
                if($goods_info['stock'] <= 0 || $goods_info['sku_stock'] <= 0){
                    return [ 'code'=>Code::FAILED , 'msg'=> '当前商品规格库存不足' ];
                }

                //日志 保存下当时结算价格
                $this->writeLog('price',"订单：" . $temp['orderId'] .
                    "商品：" . $value['goods_spu'] .
                    "规格：" . $value['sku_id'] .
                    "价格：" . $goods_info['sku_price']);

                //临时打个布丁
                $_syst_goods = (new \catchAdmin\externalGoods\model\Goods())->where('goods_spu',$value['goods_spu'])->find();
                if($_syst_goods['is_sale'] != 1){
                    return [ 'code'=>Code::FAILED , 'msg'=> '商品已下架～' ];
                }
                if($_syst_goods['stock'] <= 0){
                    return [ 'code'=>Code::FAILED , 'msg'=> '当前商品规格库存不足～' ];
                }
                $_syst_goods_rule = (new GoodsRule())
                    ->where('goods_spu',$value['goods_spu'])
                    ->where('goods_sku',$value['sku_id'])
                    ->find();
                if(!$_syst_goods_rule){
                    return [ 'code'=>Code::FAILED , 'msg'=> '当前商品规格不存在、或已下架～' ];
                }
                if($_syst_goods_rule['sku_stock'] <= 0){
                    return [ 'code'=>Code::FAILED , 'msg'=> '当前商品规格库存不足～' ];
                }
                //布丁结束


//                $temp['goods_name'] = $goods_info['goods_name']. ' ' . $goods_info['sku_name'];
                $temp['goods_supplier_id'] = $goods_info['supplier_id'];
                $temp['goods_name'] = $goods_info['goods_name'];
                $temp['GCode'] = Db::table('db_syst_sync_goods')->where('goods_spu',$value['goods_spu'])->value('barcode');
                $temp['price'] = $value['goods_price'];
                $temp['amout'] = $temp['price'] * $temp['num'];//商品总金额
                $temp['goods_url'] = 'http://hg.qekj.net/#/goodsDetail?goods_spu=' . $value['goods_spu'];

                //2024 0422新增参数
                $temp['sku_id'] = $value['sku_id'];
                $temp['sku_name'] =  $goods_info['sku_name'];
                $temp['trade_type_name'] =  $goods_info['trade_type_name'];

                $tenantGoodsService = new TenantGoodsService;
                $temp['tenant_goods_price'] =   $tenantGoodsService
                    ->getTenantGoodsSkuPrice($this->merchantInfo['tenant_id'],$value['goods_spu'],$value['sku_id']);
                $temp['headImg'] = $goods_info['goods_img'];

                //订单类型
                if(0 == $temp['goods_supplier_id']){
                    array_push($needUpdateOrder,$temp['orderId']);
                }

                $value = $temp;
                //$value = array_merge($value,$temp);
            }

            // 启动事务
            Db::startTrans();
            try {
                $returnPayInfoArr = [];
                foreach ($orderData as &$value){
                    //补充字段
                    //$insert['orderId'] = $data['merOrderId'];
                    $value['orderDate'] = date('Y-m-d H:i:s') ;//订单日期
                    $value['_ext_data'] = $value;
                }

                $res1 =  (new customsOrder)->limit(200)->insertAll($orderData);
                $res2 =  (new customsOrderSon())->limit(200)->insertAll($orderSonData);

                $res3 = true;
                if(!empty($needUpdateOrder)){
                    $needUpdateOrder = array_values(array_unique($needUpdateOrder));
                    // 11 代表 扬州保税订单
                    $res3 =  (new customsOrder())->whereIn('orderId',$needUpdateOrder)->update(['_order_type'=>11]);
                }
                
                if($res1&&$res2&&$res3){
                    // 提交事务
                    Db::commit();
                    return [ 'code'=>Code::SUCCESS , 'msg'=> '新增成功' , 'data'=> $returnPayInfoArr];
                }else{
                    Db::rollback();
                    return [ 'code'=>Code::FAILED , 'msg'=> '新增失败'];
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
            }
        }else{
            return [ 'code'=>Code::FAILED , 'msg'=> '没有订单或商品数据'];
        }
    }

    //吉客运推送
    protected function pushJKOrder($data)
    {
        $orderData = [];//主订单信息
        $orderSonData = [];//子订单信息

        $orderKeys = ['orderId','contactName','contactMobile','area_id','detailAddr','order_goods', 'amount', 'distributionfee', 'discount', 'realPayment','ebpCode','ebpName','paycomCode','paycomName','payOrderNo','contactAddr'];
        //保税
        $orderKeys_1 = ['contactCode','buyerName','ConsigneeCode','source_platform_no','pay_type','pay_time'];
        //香港直邮
        $orderKeys_4 = ['contactCode'];
        //海外直邮
        $orderKeys_5 = ['contactCode','id_card_front_img','id_card_back_img'];

        //$orderKeys = ['payerAccount','username','user_phone','area_id','user_address','orderId','order_goods', 'amount', 'distributionfee', 'discount', 'realPayment'];

        //订单商品字段
        $goodsKeys = ['goods_spu','sku_id','goods_num','goods_price','goods_name','GCode','sku_name','goods_img'];
//        $goodsKeys_1 = ['goods_spu','sku_id','goods_num','goods_price'];

        $systGoodsModel = new externalGoodsModel;

        $msg = "";
        foreach ($data as $key => $value){
            $checkValueResult = $this->check_fields($value, $orderKeys,true);//验证字段
            //判断参数
            if(!is_array($checkValueResult)){
                $msg = 'data['.$key .']'.$checkValueResult;
                break;
            }

            //2.判断订单号是否已经存在
            $flag = Db::table('db_customs_order')
                ->field('id')
                ->where(['orderId' => $value['orderId'], 'deleteStatus' => 0, 'status' => 0, 'tenant_id' => $this->merchantInfo['tenant_id']])
                ->find();
            if($flag){
                $msg = '订单号'.$value['orderId'].'已存在';
                break;
            }

            /**
             *

            $all_goods_spu_arr = array_column($value['order_goods'],'goods_spu');
            $goods_spu_trade_type_arr = $systGoodsModel->where('goods_spu','in',$all_goods_spu_arr)->column('trade_type_id');
            //3.订单商品，多个商品，判断都是同一类型
            if(1 < count($value['order_goods'])){
                $IndexService = new IndexService;
                if($IndexService->checkTwoTradeType($goods_spu_trade_type_arr)){
                    $msg = '贸易类型错误、存在多个贸易类型';
                    break;
                }
            }
             *
             *
             */


            /**
             *
            //if(!empty(array_intersect($goods_spu_trade_type_arr,[1]))){ //只有保税直供。 跨境商品，需要推送支付单
            if(!empty(array_intersect($goods_spu_trade_type_arr,[1,4,5]))){
                //只有保税直供。 跨境商品，需要推送支付单
                //2024 0518修改为 这三种贸易类型都需要推送支付单（候鸟仅保税需要，其他可以无视）
                $value['is_need_push_payment_order'] = 1;
                $value['tradeType'] = '0004';
            }else{
                $value['tradeType'] = '0002';
            }
             *
             */

            $value['is_need_push_payment_order'] = 1;
            $value['tradeType'] = '0004';


            foreach ($value['order_goods'] as $k => &$v){
                //$trade_type_id = $systGoodsModel->where('goods_spu',$v['goods_spu'])->value('trade_type_id');
//                if(1 == $trade_type_id){
//                    $checkVResult1 = $this->check_fields($value, $orderKeys_1,true);//验证字段
//                }elseif (4 == $trade_type_id){
//                    $checkVResult1 = $this->check_fields($value, $orderKeys_4,true);//验证字段
//                }elseif (5 == $trade_type_id){
//                    $checkVResult1 = $this->check_fields($value, $orderKeys_5,true);//验证字段
//                }elseif(null == $trade_type_id){
//                    $msg = '商品spu错误、或者商品贸易类型错误';
//                    break;
//                }else{
//                    $checkVResult1 = [];
//                }
                $checkVResult1 = $this->check_fields($value, $orderKeys_1,true);//验证字段

                if(!is_array($checkVResult1)){
                    $msg = 'data['.$key .']'.$checkVResult1;
                    break 2;
                }

//                $checkVResult = $this->check_fields($v, $goodsKeys,true);//验证字段
//                if(!is_array($checkVResult)){
//                    $msg = 'data['.$key .'],'.'order_goods['.$k .'],'.$checkVResult;
//                    break 2;
//                }

                $v['orderId'] = $value['orderId'];
                $orderSonData[] = $v;
            }
            $value['tenant_id'] = $this->merchantInfo['tenant_id'];//电商商户
            unset($value['goodsInfo']);
            $orderData[] = $value;
            unset($value);
        }

        //dd($orderData);

        if($msg !== ""){
            return [ 'code'=>Code::FAILED , 'msg'=> $msg ];
        }

        if(count($orderData)>0 && count($orderSonData)>0){
            foreach ($orderData as &$value){
                //dd($value);
                $temp = [];
                $temp['_order_type'] = 10;//订单类型 吉客云订单
                $temp['tenant_id'] = $value['tenant_id'];
                $temp['orderId'] = $value['orderId'];//订单iD
//                $temp['source_platform_no'] = $value['source_platform_no'] ?? '';//申报订单编号

                //订单默认日期
                if(array_key_exists('orderDate',$value)){
                    $temp['orderDate'] =   date("Y-m-d H:i:s",strtotime($value['orderDate'])  ?? time());
                }else{
                    $temp['orderDate'] = date("Y-m-d H:i:s");
                }

                $temp['create_time'] = strtotime($temp['orderDate']);

                $value['area_id'] = '000000';

                /*
                if('000000' != $value['area_id']){
                    $isActiveAreaId = Db::table('db_syst_sync_areas')->where('pid',$value['area_id'])->count();
                    $isActiveAreaId2 = Db::table('db_syst_sync_areas')->where('area_id',$value['area_id'])->find();

                    if($isActiveAreaId > 0 || empty($isActiveAreaId2)){
                        return [ 'code'=>Code::FAILED , 'msg'=> '区域ID不存在，或者区域ID不是最下级'];
                    }
                }else{
                    //收货地址
                    $area_id = Db::table('db_syst_sync_areas')->where('full_area_name',$value['full_area_name'])->value('area_id');
                    if(empty($area_id))   return [ 'code'=>Code::FAILED , 'msg'=> '收货地址区划错误，直辖市精确到街道，其他精确到区/县'];

                    //如果是直辖市，直接取街道的地址
                    $area_son_id =  Db::table('db_syst_sync_areas')->where('pid',$area_id)->value('area_id');
                    if($area_son_id) $area_id = $area_son_id;
                    $value['area_id'] = $area_id;
                    unset($value['full_area_name']);
                }
                */

                $temp['HNACARD'] = array_key_exists('HNACARD',$value) ? $value['HNACARD'] : '0';

                //扩展数据
                $temp['_ext_data'] = json_encode(array_merge($temp,$value));
                $value = array_merge($value,$temp);

//                $value = $temp;
            }

            foreach ($orderSonData as &$value){
                $temp = [];
//                $temp['tenant_id'] = $value['tenant_id'];
                $temp['orderId'] = $value['orderId'];
//                $temp['productId'] = $value['goods_spu'] . ',' . $value['sku_id'];
                $temp['productId'] = $value['goods_spu'];
                $temp['num'] = $value['goods_num'];

                /*
//                $goods_info = Db::table('db_syst_sync_goods_rule sr')
                $goods_info = Db::table('db_tenant_goods_rule sr')
                    ->field('sr.sku_name,sg.goods_name,sg.is_sale,sg.stock,sr.sku_stock,sr.sku_price,sg.trade_type_name,sg.goods_img')
                    ->leftJoin('db_tenant_goods sg','sr.goods_id = sg.id')
                    ->where('sr.goods_spu',$value['goods_spu'])
                    ->where('sr.goods_sku',$value['sku_id'])
                    ->where('sr.tenant_id',$this->merchantInfo['tenant_id'])
                    ->where('sg.deleted_at',0)
                    ->order('sr.id','desc')
                    ->find();
                if(!$goods_info){
                    return [ 'code'=>Code::FAILED , 'msg'=> '商品未添加、或商品不存在该spu或sku' ];
                }
                if($goods_info['is_sale'] != 1){
                    return [ 'code'=>Code::FAILED , 'msg'=> '商品已下架' ];
                }
                if($goods_info['stock'] <= 0 || $goods_info['sku_stock'] <= 0){
                    return [ 'code'=>Code::FAILED , 'msg'=> '当前商品规格库存不足' ];
                }

                //日志 保存下当时结算价格
                $this->writeLog('price',"订单：" . $temp['orderId'] .
                    "商品：" . $value['goods_spu'] .
                    "规格：" . $value['sku_id'] .
                    "价格：" . $goods_info['sku_price']);

                //临时打个布丁
                $_syst_goods = (new \catchAdmin\externalGoods\model\Goods())->where('goods_spu',$value['goods_spu'])->find();
                if($_syst_goods['is_sale'] != 1){
                    return [ 'code'=>Code::FAILED , 'msg'=> '商品已下架～' ];
                }
                if($_syst_goods['stock'] <= 0){
                    return [ 'code'=>Code::FAILED , 'msg'=> '当前商品规格库存不足～' ];
                }
                $_syst_goods_rule = (new GoodsRule())
                    ->where('goods_spu',$value['goods_spu'])
                    ->where('goods_sku',$value['sku_id'])
                    ->find();
                if(!$_syst_goods_rule){
                    return [ 'code'=>Code::FAILED , 'msg'=> '当前商品规格不存在、或已下架～' ];
                }
                if($_syst_goods_rule['sku_stock'] <= 0){
                    return [ 'code'=>Code::FAILED , 'msg'=> '当前商品规格库存不足～' ];
                }
                //布丁结束
                    */

//                $temp['goods_name'] = $goods_info['goods_name']. ' ' . $goods_info['sku_name'];
                $temp['goods_name'] = $value['goods_name'];
                $temp['GCode'] = $value['GCode'];
                //$temp['GCode'] = Db::table('db_syst_sync_goods')->where('goods_spu',$value['goods_spu'])->value('barcode');
                $temp['price'] = $value['goods_price'];
                $temp['goods_url'] = 'http://hg.qekj.net/#/goodsDetail2?goods_spu=' . $value['goods_spu'];

                //2024 0422新增参数
                $temp['sku_id'] = $value['sku_id'];
                $temp['sku_name'] =  $value['sku_name'];
                $temp['trade_type_name'] = '保税商品';

//                $tenantGoodsService = new TenantGoodsService;
//                $temp['tenant_goods_price'] =   $tenantGoodsService
//                    ->getTenantGoodsSkuPrice($this->merchantInfo['tenant_id'],$value['goods_spu'],$value['sku_id']);
                $temp['headImg'] = $value['goods_img'];

                $value = $temp;
                //$value = array_merge($value,$temp);
            }

            // 启动事务
            Db::startTrans();
            try {
                $returnPayInfoArr = [];
                foreach ($orderData as &$value){
                    /*
                    $_merge_data = ['toReturnUrl'=>$value['returnUrl'], 'toNoticeUrl'=>$value['noticeUrl']];

                    $apiPayData = [];
                    $apiPayData['merOrderId'] = $value['orderId'];
                    $apiPayData['displayName'] = mb_substr($orderSonData[0]['goods_name'],0,50);
                    $apiPayData['goodsName'] = mb_substr($orderSonData[0]['goods_name'],0,50);
                    $apiPayData['goodsCount'] = array_sum(array_column($value['order_goods'],'goods_num')) ;
                    $apiPayData['goodsType'] = '06';
                    $apiPayData['orderAmount'] =  (int) ($value['realPayment'] * 100);
                    $apiPayData['orderCurrencyCode'] = 'CNY';
                    $apiPayData['tradeType'] = '0004'; //  "tradeType":"0002",
                    $apiPayData['payType'] = '4';//预付卡
                    $apiPayData['orgCode'] = 'WECHATPAY';
                    $apiPayData['payerAccount'] = $value['payerAccount'];
                    $apiPayData['payCurrencyCode'] = 'CNY';
                    $apiPayData['settleCurrencyCode'] = 'CNY';
                    $apiPayData['shareFlag'] = '0';
                    $apiPayData['returnUrl'] = 'http://cross.qekj.net/callback/xinsheng';
                    $apiPayData['noticeUrl'] = 'http://cross.qekj.net/callback/xinsheng';
                    $apiPayData['customerType'] = '1';
                    $apiPayData['declareCheck'] = "1"; //验证
                    $apiPayData['customerName'] = $value['buyerName'];
                    $apiPayData['customerIdNo'] = $value['ConsigneeCode'];
                    $apiPayData['customerTel'] = $value['contactMobile'];

                    //dd($apiPayData);

                    //文档参数顺序
                    $req_key = ['merOrderId','displayName','goodsName','goodsCount','goodsType','orderAmount','orderCurrencyCode','tradeType',
                        'payType','orgCode','payerAccount','payCurrencyCode','settleCurrencyCode','shareFlag','subMerchantOrderDetails','returnUrl',
                        'noticeUrl','platformId','customerId','customerType','customerName','customerIdNo','customerTel'
                        ,'bankCardNo','bankCardType','expireData','cvn','remark','reserve1','reserve2','preOrderFlag','declareCheck'
                    ];
                    //新生支付，参数有顺序要求。必须按照文档来
                    $apiPayData = getAfterSortByKeys($req_key,$apiPayData);

                    $xinshengApi = new Pay($this->_par);

                    $result = $xinshengApi->apiPay($apiPayData);

                    //dd($result);

                    $value = array_merge($value,$apiPayData, [
                        '_xs_apipay_return_data'=>$result['content'],
                        'xs_status'=>$result['content']['status'],
                        'dealId'=>$result['content']['dealId'],
                        '_random_orderId'=>$result['head']['orderId'],
                        'tenant_id'=>$this->merchantInfo['tenant_id'],
                    ],$_merge_data);
                    $value['payInfo'] = $result['content']['payInfo'];
                    $returnPayInfoArr[ $apiPayData['merOrderId'] ] =  $value['payInfo'];

                    */

                    //扩展字段
                    //补充字段
                    //$insert['orderId'] = $data['merOrderId'];

                    $value['orderDate'] = date('Y-m-d H:i:s') ;//订单日期

                    //$value['realPayment'] =  number_format($result['content']['payAmount']  / 100 ,2);;//实际付款金额

                    $value['_ext_data'] = $value;
                    //(new customsOrder)->save($insert);
                }

                $res1 =  (new customsOrder)->limit(200)->insertAll($orderData);
                $res2 =  (new customsOrderSon())->limit(200)->insertAll($orderSonData);

//                $res1 = Db::table('db_customs_order')->limit(200)->insertAll($orderData);
//                $res2 = Db::table('db_customs_orderlist')->limit(200)->insertAll($orderSonData);

                if($res1&&$res2){
                    // 提交事务
                    Db::commit();
                    return [ 'code'=>Code::SUCCESS , 'msg'=> '新增成功' , 'data'=> $returnPayInfoArr];
                }else{
                    Db::rollback();
                    return [ 'code'=>Code::FAILED , 'msg'=> '新增失败'];
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
            }
        }else{
            return [ 'code'=>Code::FAILED , 'msg'=> '没有订单或商品数据'];
        }
    }

    /**
     * 接收推送订单
     * @param  $data
     * @return array
     */
    protected function pushOrder($data)
    {
        $orderData = [];//主订单信息
        $orderSonData = [];//子订单信息

        //订单字段
        $orderKeys = ['orderId', 'orderDate', 'amount', 'distributionfee', 'discount', 'tax', 'realPayment', 'currency', 'ebpCode', 'ebpName', 'ConsigneeCode', 'buyerName', 'paycomCode', 'paycomName', 'payOrderNo', 'contactName', 'contactMobile', 'contactAddr', 'detailAddr', 'postcode',  'note', 'goodsInfo'];

        //订单商品字段
        $goodsKeys = ['orderId', 'RecordMaterialNo', 'goods_name', 'GCode', 'barcode', 'num', 'price', 'amout', 'spec_qty', 'note'];

        $msg = "";
        foreach ($data as $key => $value){
            $value = $this->check_fields($value, $orderKeys,true);//验证字段
            //判断参数
            if(!is_array($value)){
                $msg = 'data['.$key .']'.$value;
                break;
            }
            if(empty($value['orderId'])){
                $msg = 'data['.$key .']，orderId不合法';
                break;
            }

            if($value['realPayment'] > 5000){
                $msg = 'data['.$key .']，单笔订单实付款不能超过5000元';
                break;
            }

            $flag = Db::table('db_customs_order')
                ->field('id')
                ->where(['orderId' => $value['orderId'], 'deleteStatus' => 0, 'status' => 0, 'tenant_id' => $this->merchantInfo['tenant_id']])
                ->find();

            if($flag){
                $msg = '订单号'.$value['orderId'].'已存在';
                break;
            }

            foreach ($value['goodsInfo'] as $k => $v){
                $v = $this->check_fields($v, $goodsKeys,true);//验证字段
                //判断参数
                if(!is_array($v)){
                    $msg = 'data['.$key .'],'.'goodsInfo['.$k .'],'.$v;
                    break 2;
                }

                $flag = Db::table('db_customs_record_material')
                    ->field('id')
                    //->where(['orderId' => $value['orderId'], 'deleteStatus' => 0, 'status' => 0, 'tenant_id' => $this->merchantInfo['tenant_id']])
                    ->where(['barcode' => $v['barcode'],'record_material_no' => $v['RecordMaterialNo']])
                    ->find();
                if(!$flag){
                    $msg = 'data['.$key .'],'.'goodsInfo['.$k .']账册料号'.$v['RecordMaterialNo'].'条形码'.$v['barcode'].'没有账册备案信息';
                    break 2;
                }

                $v['Qty'] = $v['num'];
                $orderSonData[] = $v;
                unset($v);

            }
            $value['tenant_id'] = $this->merchantInfo['tenant_id'];//电商商户
            $value['completeDateTime'] = date('YmdHis');//时间
            $value['copNo'] = $this->getCopNo();
            unset($value['goodsInfo']);
            $orderData[] = $value;
            unset($value);
        }
        if($msg !== ""){
            return [ 'code'=>Code::FAILED , 'msg'=> $msg ];
        }

        if(count($orderData)>0 && count($orderSonData)>0){
            // 启动事务
            Db::startTrans();
            try {
                $res1 = Db::table('db_customs_order')->limit(200)->insertAll($orderData);
                $res2 = Db::table('db_customs_orderlist')->limit(200)->insertAll($orderSonData);
                if($res1&&$res2){
                    // 提交事务
                    Db::commit();
                    return [ 'code'=>Code::SUCCESS , 'msg'=> '新增成功' , 'data'=>[]];
                }else{
                    Db::rollback();
                    return [ 'code'=>Code::FAILED , 'msg'=> '新增失败'];
                }

            } catch (\Exception $e) {

                return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
                // 回滚事务
                Db::rollback();
            }
        }else{
            return [ 'code'=>Code::FAILED , 'msg'=> '没有订单或商品数据'];

        }
    }
    /**
     * 查询订单
     * @param  $data
     * @return array
     */
    protected function queryOrder($data)
    {
        $keys = ['orderId'];
        $value = $this->check_fields($data, $keys,true);//验证字段
        //判断参数
        if(!is_array($value)){
            return [ 'code'=>Code::FAILED , 'msg'=> $value];

        }

        $data = Db::table('db_customs_order')
            ->field('orderId,express_company as expressCompany,express_no as expressNo,push_order as orderStatus,push_inventory as inventoryStatus')
            ->where(['orderId' => $data['orderId'], 'deleteStatus' => 0, 'status' => 0,'tenant_id' => $this->merchantInfo['tenant_id']])
            ->find();

        if($data){
            return ['code'=>Code::SUCCESS, 'msg' => '查询成功', 'data' => $data];

        }else{
            return ['code'=>Code::FAILED, 'msg' => '订单号不存在'];

        }
    }

    /**
     * 删除订单
     * @param  $data
     * @return array
     */
    protected function cancelOrder($data)
    {
        $keys = ['orderId'];
        $value = $this->check_fields($data, $keys,true);//验证字段
        //判断参数
        if(!is_array($value)){
            return [ 'code'=>Code::FAILED , 'msg'=> $value];

        }

        Db::startTrans();
        try {
            $info = Db::table('db_customs_order')
                ->field('id,push_inventory')
                ->where(['orderId' => $data['orderId'], 'tenant_id' => $this->merchantInfo['tenant_id'],'status'=>0,'deleteStatus'=>0])
                ->find();
            if(!$info){
                return ['code'=>Code::FAILED, 'msg' => '不存在的订单号'];
            }

            //1:电子口岸已暂存/2:电子口岸申报中/3:发送海关成功/120:海关入库  申报中
            if($info['push_inventory'] === 1||$info['push_inventory'] === 2||$info['push_inventory'] === 3||$info['push_inventory'] === 120){
                return ['code'=>Code::FAILED, 'msg' => '申报中，暂不可以取消订单'];
            }
            //300:人工审核/800:放行
            if($info['push_inventory'] === 300||$info['push_inventory'] === 800){
                return ['code'=>Code::LIMIT_CANCEL, 'msg' => '已放行，不可以取消订单'];
            }

            $res = Db::table('db_customs_order')
                ->where(['orderId' => $data['orderId'], 'tenant_id' => $this->merchantInfo['tenant_id']])
                ->save(['status'=>1,'deleteStatus'=>1,'modifyTime' => date('Y-m-d H:i:s')]);

            $res1 = Db::table('db_customs_orderlist')
                ->where(['orderId' => $data['orderId']])
                ->save(['deleteStatus'=>1]);

            if($res&&$res1){
                Db::commit();
                return ['code'=>Code::SUCCESS, 'msg' => '取消成功', 'data' => []];

            }else{
                Db::rollback();
                return ['code'=>Code::FAILED, 'msg' => '取消失败'];

            }

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];

        }
    }

    /**
     * 验证token
     * @param Request $request
     * @return string
     */
    public function checkSign(Request $request)
    {

        try {
            $data = $request->param();
            $keys = ['merchantId','timeStamp','secret'];
            $value = $this->check_fields($data, $keys, true);//验证字段
            //判断参数
            if(!is_array($value)){
                return CatchResponse::fail($value, Code::FAILED);

            }
            $signList = $this->get_sign($data, $data['secret']);
            return CatchResponse::success($signList, '成功', Code::SUCCESS);
        } catch (\Exception $e) {
            return CatchResponse::fail($e->getMessage(), Code::FAILED);
        }

    }
    /**
     * 生成签名
     * @param $params
     * @param $secret
     * @return string
     */
    protected function get_sign($params, $secret) {
        unset($params['sign']);
        unset($params['secret']);
        //签名步骤一：按字典序排序参数
        ksort($params);
        $str = '';

        //签名步骤二：键名键值依次拼接,最后拼接密钥
        foreach ($params as $k => $v) {
            $str .= $k . $v;
        }
        $str = $str . $secret;
        $signList['step2'] = $str;//签名步骤2
        //echo '签名步骤二：'.$str;
        //签名步骤三：base64_encode加密
        $str = base64_encode($str);
        $signList['step3'] = $str;//签名步骤3
        //签名步骤四：md5加密
        $str = md5($str);
        $signList['step4'] = $str;//签名步骤4
        //签名步骤五：所有字符转为大写
        $str = strtoupper($str);
        $signList['step5'] = $str;//签名步骤5
        $signList['sign'] = $str;//签名
        return $signList;
    }
    /**
     * 验证字段缺失 可扩展
     * @param $params 关联数组
     * @param $fields 字段名数组 一维索引数组
     * @param $back 不满足是否返回
     * @return string
     */
    protected function check_fields($params, $fields, $back){
        if(!is_array($params)){
            return '数据格式错误';

        }
        $err = false;
        $deal_params = [];

        foreach ($fields as $value) {
            if(!array_key_exists($value, $params)){
                if($back){
                    $err = '缺少字段'.$value;
                    break;
                }

            }else{
                $deal_params[$value] = $params[$value];

            }

        }
        if($err === false){
            return $deal_params;
        }else{
            return $err;
        }

    }

    /**
     * token创建
     * @param $info
     * @return string
     */
    protected function jwt($info)
    {
        $token = JWTAuth::builder(['merchantInfo' => $info]);

        JWTAuth::setToken($token);

        return $token;
    }
    /**
     * 写入日志
     * BASE_PATH 在入口文件设置
     */
    protected function writeLog($type,$text)
    {
        $now = date('Y-m-d H:i:s');
        $ip = request()->ip();
        $log_path = "log/api/{$type}/";
        $destination = $log_path.date('y_m_d').'.log';
        if(!is_dir($log_path)) {
            mkdir($log_path,0755,true);
        }
        error_log("[{$now}] ".$_SERVER['REMOTE_ADDR'].' '.$_SERVER['REQUEST_URI'].'  IP:'.$ip."\r\n{$text}\r\n", 3,$destination);
    }

    /**
     * 生成企业标识唯一编号
     * @time 2022/02/15 11:41
     * @return string
     */
    protected function getCopNo(){
        $code = substr(md5(uniqid(rand(), true)),0,20);
        $copNo = Db::table('db_customs_order')
                ->where(['copNo' => $code])
                ->find();
        if(!empty($copNo)){
            return $this->getCopNo();
        }else{
            return $code;
        }
    }

    protected function checkIsEmptyForBaoShui($data){
        $result = false;
//        $all = ['id_card','ebpCode','ebpName','declarer','declarer_id_card',
//            'source_platform_no','amount_freight','amount_discount','amount_paid_in','pay_type','pay_no','pay_time'
//        ];

        $all = ['id_card','ebpCode','ebpName','declarer','declarer_id_card',
            'source_platform_no','amount_freight','amount_discount','amount_paid_in','pay_type','pay_no','pay_time'
        ];

        foreach ($all as $value){
            if(!array_key_exists($value,$data) || empty($data[$value])){
                $result = $value;
                break;
            }
        }

        return $result;
    }
}
